'use strict';

// 获取moment工具
const moment = require('moment');

// 有效时间为30分钟
module.exports = {
  getToken(options) {
    console.log(this.app);
    return this.app.jwt.sign(options, this.app.config.jwt.secret, { expiresIn: '3600s' });
  },

  // 格式化接口响应body
  formatResponse(data, code = 200, msg = '') {
    return {
      code,
      msg,
      data,
    };
  },

  getRandom(min, max) {
    return Math.round(Math.random() * (max - min) + min);
  },

  // 获得6位邮箱验证码，每位数字可能为大写字母/小写字母/数字
  getVerifyCode() {
    let code = '';
    for (let i = 0; i < 6; i++) {
      const getRandom = this.getRandom;
      const type = getRandom(1, 3);
      switch (type) {
        case 1:
          code += String.fromCharCode(getRandom(48, 57));// 数字
          break;
        case 2:
          code += String.fromCharCode(getRandom(65, 90));// 大写字母
          break;
        case 3:
          code += String.fromCharCode(getRandom(97, 122));// 小写字母
          break;
        default:
        // do nothing
      }
    }
    return code;
  },

  // 获取当前时间戳
  getCurrentDatetime() {
    const currentDatetime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    return currentDatetime;
  },


  // 字符串的下划线格式转驼峰格式，eg：hello_world => helloWorld
  underline2Hump(s) {
    return s.replace(/_(\w)/g, function(all, letter) {
      return letter.toUpperCase();
    });
  },

  // JSON对象的key值转换为驼峰式
  jsonToHump(obj) {
    if (obj instanceof Array) {
      obj.forEach(v => {
        this.jsonToHump(v);
      });
    } else if (obj instanceof Object) {
      Object.keys(obj).forEach(key => {
        const newKey = this.underline2Hump(key);
        if (newKey !== key) {
          obj[newKey] = obj[key];
          delete obj[key];
        }
        this.jsonToHump(obj[newKey]);
      });
    }
    return obj;
  },

  // 字符串的驼峰格式转下划线格式，eg：helloWorld => hello_world
  hump2Underline(s) {
    return s.replace(/([A-Z])/g, '_$1').toLowerCase();
  },


  // JSON对象的key值转换为下划线格式
  jsonToUnderline(obj) {
    if (obj instanceof Array) {
      obj.forEach(v => {
        this.jsonToUnderline(v);
      });
    } else if (obj instanceof Object) {
      Object.keys(obj).forEach(key => {
        const newKey = this.hump2Underline(key);
        if (newKey !== key) {
          obj[newKey] = obj[key];
          delete obj[key];
        }
        this.jsonToUnderline(obj[newKey]);
      });
    }
    return obj;
  },

  // 获取阿里云oss文件夹和文件名
  getOssFilename(obj, prefix) {
    const index = obj.lastIndexOf(prefix);
    obj = obj.substring(index + prefix.length, obj.length);
    return obj;
  },

  // 获取hash_code
  getHashCode(tensor) {
    if (!tensor) { return '122312'; }
    const str1 = tensor.slice(8, -2); // 获取tensor值的部分
    const str2 = str1.replaceAll(' ', '').replaceAll('-1.', '0').replaceAll('1.', '1'); // 去除空格,用0代替-1.,用1代替1.
    const str3 = str2.split(',').join('');
    return str3;
  },

};
